package com.example.smartwaterapi;

import com.example.smartwaterapi.entity.User;
import com.example.smartwaterapi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
@SpringBootApplication
@EnableScheduling
@MapperScan("com.example.smartwaterapi.mapper")
public class SmartWaterApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(SmartWaterApiApplication.class, args);
    }
  
    @Bean
    public ApplicationRunner initializeTestUser(
            @Autowired UserService userService,
            @Autowired PasswordEncoder passwordEncoder) {

        return args -> {
            try {
                // 检查是否已存在测试用户
                User existingUser = userService.getByPhone("13800138000");
                if (existingUser == null) {
                    log.info("创建测试用户...");

                    // 创建测试用户
                    User testUser = new User();
                    testUser.setPhone("13800138000");
                    testUser.setNickname("测试账号");
                    testUser.setUnlockPassword(passwordEncoder.encode("123456"));
                    testUser.setPasswordSalt(UUID.randomUUID().toString().replace("-", ""));
                    testUser.setUuid(UUID.randomUUID().toString().replace("-", ""));
                    testUser.setStatus(1);
                    testUser.setAvatar("https://xinhangda.tos-cn-guangzhou.volces.com/default-avatar.png");
                    testUser.setGender(1);
                    testUser.setDailyGoal(2000);
                    testUser.setReminderEnabled(1);
                    testUser.setReminderInterval(60);
                    testUser.setMembershipLevel("basic");
                    testUser.setPoints(100);
                    testUser.setTotalPoints(100);
                    testUser.setCreatedAt(LocalDateTime.now());
                    testUser.setUpdatedAt(LocalDateTime.now());
                    userService.save(testUser);
                    log.info("测试用户创建成功! 手机号: 13800138000, 密码: 123456");
                } else {
                    log.info("测试用户已存在，跳过创建");
                }
            } catch (Exception e) {
                log.error("创建测试用户失败", e);
            }
        };
    }
}
